<?php
namespace app\api\controller;
/*聊天控制器*/

use think\facade\Db;
use think\Request;
use app\BaseController;
use app\common\controller\ApiController;
use think\App;

class Chat extends ApiController
{

    public function initialize()
    {
        parent::initialize();
        $this->store = app('app\common\model\mall\Store');
        $this->account = app('app\common\model\mall\Account');
        $this->account_item = app('app\common\model\media\AccountItem');
        $this->user = app('app\common\model\user\WxUsers');
        $this->order = app('app\common\model\mall\Order');
        $this->chat_message = app('app\common\model\chat\ChatMessage');


    }
    //查看订单
    public function order(Request $request){
        $model = $this->order;
        $where = [
            'user_id'=>$request->param('user_id'),
            'type'=>$request->param('type',0),
            'store_id'=>$request->param('store_id'),
        ];
        $res = $model->where($where)->with('goods')->order('create_time','desc')
                ->paginate($request->param('limit',10))->all();


        return json(['code'=>200,'msg'=>'获取成功','data'=>$res]);
    }

    /*商品列表*/
    public function goods(Request $request)
    {

        $model = $this->account;

        $model = $model->where(['status'=>1,'type'=>2,'store_id'=>$request->param('store_id')]);
        $request->param('category_id') && $model = $model->where('category_id',$request->param('category_id'));
        if($request->param('name')){
            $model = $model->where('title','like','%'.$request->param('name').'%');
        }

        $res = $model->paginate($request->param('limit',10))->all();

        return json(['code'=>200,'msg'=>'获取成功','data'=>$res]);
    }

    public function check_str($str, $substr)
    {
        $nums=substr_count($str,$substr);
        if ($nums>=1)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    /**
     * 获取信息
     * @param Request $request
     */
    public function chat_message(Request $request)
    {

       $account_id = $request->param('from');

       $to_id = $request->param('to_id');


       $type = $request->param('type',1); //1:用户对商家；2：用户对平台;3:商家对用户；4：平台对用户

        switch($type){
            case 1:$types = [1,3];break;
            case 2:$types = [4,2];break;
            case 3:$types = [1,3];break;
            case 4:$types = [1,4];break;
            default :$types = [1,3];
        }

       /* $ress = $this->chat_message->field('id,content,create_time,msgtype,type,to_id,from_id')
           //->name('chat_message')
           ->where(['to_id'=>$to_id,'from_id'=>$account_id])
           ->union(function($query) use($to_id,$account_id){
               $query->field('id,content,create_time,msgtype,type,to_id,from_id')
                   ->name('chat_message')
                   ->where(['from_id'=>$to_id,'to_id'=>$account_id]);
           })->order('create_time','asc')->select()->toArray();
       foreach ($ress as $k=>$v){
           if($v['msgtype'] ==3){
               $ress[$k]['item_info'] = $this->account->find($v['content']);
           }
       }

        //重新获取已读未读数据
        $ids = array_column($ress,'id');*/


        $time = time();
        //dd($account_id);
       // dd($ids);
       //自己发送的标记已读
        $this->chat_message->where(['from_id'=>$account_id,'to_id'=>$to_id])/*->whereIn('type',$types)*/->where('create_time','<',$time)->save(['see_status'=>1]);
        //接收的标记已读
        $this->chat_message->where(['from_id'=>$to_id,'to_id'=>$account_id])/*->whereIn('type',$types)*/->where('create_time','<',$time)->save(['see_status'=>2]);

        $res = $this->chat_message->field('id,content,create_time,msgtype,type,to_id,from_id')
            //->name('chat_message')
            ->where(['to_id'=>$to_id,'from_id'=>$account_id])->whereIn('type',$types)
            ->union(function($query) use($to_id,$account_id,$types){
                $query->field('id,content,create_time,msgtype,type,to_id,from_id')
                    ->name('chat_message')
                    ->where(['from_id'=>$to_id,'to_id'=>$account_id])
                    /*->whereIn('type',$types)*/
                ;
            })->order('create_time','asc')->select()->toArray();
        foreach ($res as $k=>$v){

            if($v['msgtype'] ==3){
                $res[$k]['item_info'] = $this->account->find($v['content']);
            }
        }
        //dd($res);
        //$ids = array_column($res,'id');
        return json(['code'=>200,'msg'=>'获取成功','data'=>$res]);
    }


    /**
     * 获取商家聊天列表
     * @param Request $request
     */
    public function chat_member(Request $request)
    {
        //当前账户id
        $account_id = $request->param('account_id');
        $type = $request->param('type'); //1:用户对商家；2：用户对平台;3:商家对用户；4：平台对用户

        switch($type){
            case 1:$types = [1,3];break;
            case 2:$types = [1,2];break;
            case 3:$types = [1,3];break;
        }

        $sub = Db::name('chat_message')
            ->field('to_id as uid,content,type,msgtype,see_status,create_time')
            ->where(['from_id'=>$account_id])
            ->union('SELECT from_id as uid,content,type,msgtype,see_status,create_time FROM bgt_chat_message WHERE to_id = '.$account_id)
            ->order('create_time desc')
            ->buildSql();

        $query = Db::table($sub)
            ->alias('tmp')
            ->group('tmp.uid')
            ->order('tmp.create_time desc')
            ->buildSql();

        $res = Db::table($query)
            ->alias('t')
            ->field('uid,nick_name,avatar_url,content,type,msgtype,see_status,t.create_time')
            ->join('bgt_wx_users u', 't.uid=u.id', 'LEFT')
            ->order('t.create_time desc')
            ->select()->toArray();


        foreach($res as $k=>$v){

            $res[$k]['create_time'] = date('m-d',$v['create_time']);
            if($v['msgtype'] ==3){

                $res[$k]['content'] = $this->account->where('id',$v['content'])->value('title');
            }

            if($type == $v['type'] && $v['see_status'] == 2){ //已读

                $res[$k]['see_status'] = 1;

            }elseif($type != $v['type'] && $v['see_status'] == 1){

                $res[$k]['see_status'] = 0;

            }elseif($type == $v['type'] && $v['see_status'] == 1){

                $res[$k]['see_status'] = 1;

            }elseif($type != $v['type'] && $v['see_status'] == 2){

                $res[$k]['see_status'] = 1;

            }else{
                $res[$k]['see_status'] = 0;
            }
            //$res[$k]['see_status'] = 1;
        }
        return json(['code'=>200,'msg'=>'获取成功','data'=>$res]);
     }

    /**
     * 获取商家聊天列表
     * @param Request $request
     */
    public function user_chat_member(Request $request)
    {

        //当前账户id
        $account_id = $request->param('account_id');
        $type = $request->param('type',1);

        $sub = Db::name('chat_message')
            ->field('to_id as uid, content,type,msgtype,see_status,create_time')
            ->where('from_id ='.$account_id)
            ->union('SELECT from_id as uid,content,type,msgtype,see_status,create_time FROM bgt_chat_message WHERE to_id = '.$account_id)
            ->order('create_time desc')
            ->buildSql();

        $query = Db::table($sub)
            ->alias('tmp')
            ->group('tmp.uid')
            ->order('tmp.create_time desc')
            ->buildSql();


        $res = Db::table($query)
            ->alias('t')
            ->field('t.uid,u.username,t.content,t.type,t.msgtype,t.see_status,t.create_time,s.name,s.thumb')
            ->join('bgt_system_admin u', 't.uid=u.id', 'LEFT')
            ->join('bgt_store s', 'u.store_id=s.id', 'LEFT')
            ->order('t.create_time desc')
            ->select()->toArray();


        foreach($res as $k=>$v){
            $res[$k]['see_status'] = 0;
            $res[$k]['username'] = $v['name'];
            if($v['msgtype'] !=3){
                $res[$k]['content'] = base64_decode($v['content']);
            }

            if($type == $v['type'] && $v['see_status'] == 2){ //已读

                $res[$k]['see_status'] = 1;
            }elseif($type != $v['type'] && $v['see_status'] == 1){

                $res[$k]['see_status'] = 0;
            }elseif($type == $v['type'] && $v['see_status'] == 1){
                $res[$k]['see_status'] = 1;
            }else{
                $res[$k]['see_status'] = 0;
            }

            $res[$k]['create_time'] = date('Y-m-d H:i',$v['create_time']);
            if($type == 1){

                if($v['type']== 2 || $v['type'] ==4){
                    unset($res[$k]);
                }
            }
        }
        $info = $this->user->field('id,avatar_url')->find($request->user_id)->toArray();

        return json(['code'=>200,'msg'=>'获取成功','data'=>['info'=>$info,'res'=>$res]]);
    }


}